// Sparx.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"

DWORD WINAPI HandleScript( LPVOID lpvParam ){
	char* pFilepath = reinterpret_cast<char*>(lpvParam);
	char szBuffer[1024], szAuthor[1024];
	int iBindKey;
	std::ifstream fScript( pFilepath );
	fScript.getline( szBuffer, 1024 );
	if( !strstr( szBuffer, "AUTHOR : " ) ){
		std::ofstream fLog( "Sparx.txt" );
		fLog << "Invalid script format in " << *pFilepath << " : Missing AUTHOR" << std::endl;
		fLog.close( );
		return 0;
	}
	sprintf_s( szAuthor, szBuffer + 9 );
	fScript.getline( szBuffer, 1024 );
	if( !strstr( szBuffer, "BIND : " ) ){
		std::ofstream fLog( "Sparx.txt" );
		fLog << "Invalid script format in " << *pFilepath << " : Missing BIND" << std::endl;
		fLog.close( );
		return 0;
	}
	iBindKey = atoi( szBuffer + 7 );

	while( true ){
		if( GetAsyncKeyState( iBindKey )&0x8000 ){
			fScript.getline( szBuffer, 1024 );
			if( strstr( szBuffer, "core.sleep" ) ){
				DWORD dwSleepTime = 0;
				sscanf_s( szBuffer, "core.sleep : %i", dwSleepTime );
				Sleep( dwSleepTime );
				continue;
			}
			if( strstr( szBuffer, "core.msgbox" ) ){
				char szCaption[1024], szMessage[1024];
				sscanf_s( szBuffer, "core.msgbox : \"%s\" \"%s\"", szMessage, szCaption );
				MessageBoxA( NULL, szMessage, szCaption, MB_OK );
				continue;
			}
		}
	}

}

DWORD WINAPI LoadScript( LPVOID lpvReserved ){
	std::ifstream fSettings( "Sparx.ini" );
	char szSettings[1024];
	fSettings.getline( szSettings, 1024 );
	while( szSettings ){
		CreateThread( NULL, 0, &HandleScript, &szSettings, 0, NULL );
		fSettings.getline( szSettings, 1024 );
	}
	fSettings.close( );
	return 0;
}